from google.appengine.dist import use_library
use_library('django', '1.2')

import os.path
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import memcache
from google.appengine.api import channel
from django.utils import simplejson as json
from model import *
import os
import logging

CHANNEL_NAME = 'discovery'
USER_CHANNEL = "user_channel"

class BaseRequestHandler(webapp.RequestHandler):
    """Supplies a common template generation function.

  When you call write_out(), we augment the template variables supplied with
  the current user in the 'user' variable and the current webapp request
  in the 'request' variable.
  """
    def write_out(self, template_name, template_values={}):
        values = {
            'user'      : users.get_current_user(),
            'admin_user': users.is_current_user_admin(),
            'user_valid': Member.is_user_valid(),
            'logout_url': users.create_logout_url(self.request.uri),
            'page_title': 'KhusKa'
        }
        values.update(template_values)
        self.response.out.write(self.generate(template_name, values))

    def generate(self, template_name, values):
        directory = os.path.dirname(__file__)
        path      = os.path.join(directory, os.path.join('templates', template_name))
        return template.render(path, values, debug=True)

    def _check_user(self):
        if not Member.is_user_valid():
            if not os.environ['PATH_INFO'] == '/_projects':
                self.redirect('/_projects')

    def get(self):
        self._check_user()
        try:
            self._get()
        except AttributeError:
            self.response.out.write("Bad id!!!, your id is not correct.")
            logging.exception("Bad id!!!, your id is not correct.")
        except Exception:
            self.response.out.write("Something is wrong, we will try to figure out it.")
            logging.exception("Something is wrong, we will try to figure out it.")


    def post(self):
        self._check_user()
        self._post()

    def json_format(self, response):
        return json.dumps(response)
        
    def json_response(self, response):
        self.response.headers.add_header('content-type', 'application/json', charset='utf-8')
        self.response.out.write(self.json_format(response))
        
    def not_allowed_error(self):
        response = 'Not allowed!!!'
        self.response.set_status(500)
        self.json_response(response)

    def block_error(self):
        response = 'It is being edited by another user.'
        self.response.set_status(500)
        self.json_response(response)
def set_channel_name(key, channel_name):
    memcache.set(key, channel_name)

def get_channel_name(key):
    return memcache.get(key)

def set_channel_user(channel_id, user, channel_name):
    user_channel = memcache.get(USER_CHANNEL)
    if user_channel:
        user_channel.update({channel_id: (user, channel_name)})
    else:
        user_channel = {channel_id: (user, channel_name)}


    memcache.set(USER_CHANNEL, user_channel, 30*60)
def get_online_users(channel_name):
    channel = memcache.get(channel_name)
    users = []
    if channel:
        users = channel.keys()

    return users

EDIT_LOCK_DURATION = 10*60
def acquire_lock(id):
    user = users.get_current_user()
    lock_key = str(id) + '.lock'
    lock_owner = memcache.get(lock_key)
    if lock_owner == str(user):
        return True
    if lock_owner is None:
        # Attempt to acquire lock.
        return memcache.add(
        lock_key, str(user), EDIT_LOCK_DURATION)
    else:
        return False
    
def release_lock(id):
    memcache.delete(str(id) + '.lock')